package com.probox.common.redis.service;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * spring redis 工具类
 *
 * @author usoft
 **/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisService {
    @Autowired
    public RedisTemplate redisTemplate;

    private static final Logger log = LoggerFactory.getLogger(RedisService.class);

    //一天
    public static long ONEY_DAY = 1L;

    public static long FIVEMINUTE = 5L;

    //30秒
    public static long ThirtySecond = 30L;

    public static long OneSecond = 1L;

    public static long ThreeSecond = 3L;

    public static long TenSecond = 10L;

    public static long ONEHOUR = 3600L;

    public Long incrId(String key, Long value) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        persist(key);
        Long increment = entityIdCounter.incrementAndGet();
        return value + increment;
    }

    public Long INCRBYId(String key, Long value, Long increment) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        persist(key);
        Long ement = redisTemplate.getConnectionFactory().getConnection().incrBy(redisTemplate.getKeySerializer().serialize(key), increment);
        return value + ement;
    }

    public Long incr(String key, long liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();

        if ((null == increment || increment.longValue() == 0) && liveTime > 0) {//初始设置过期时间
            entityIdCounter.expire(liveTime, TimeUnit.HOURS);
        }
        return increment;
    }

    public Long incr(String key, long liveTime, TimeUnit timeUnit) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.incrementAndGet();
        //log.info("缓存key:{}的值为:{}",key,increment);
        //初始设置过期时间
        if ((null == increment || increment.longValue() == 0 || increment.longValue() == 1) && liveTime > 0) {
            entityIdCounter.expire(liveTime, timeUnit);
        }
        return increment;
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(final String key, final Object value) {
        if (value != null) {
            redisTemplate.opsForValue().set(key, JSON.toJSONString(value), ONEY_DAY, TimeUnit.DAYS);
        }
    }

    public void set(final String key, final Object value, final Long timeout, final TimeUnit timeUnit) {
        if (value != null) {
            redisTemplate.opsForValue().set(key, JSON.toJSONString(value), timeout, timeUnit);
        }
    }


    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout) {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    public <T> T get(final String key, Class<T> c) {
        ValueOperations<String, String> operation = redisTemplate.opsForValue();
        String cache = operation.get(key);
        if (cache == null) {
            return null;
        }
        return JSON.parseObject(cache, c);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key) {
        return redisTemplate.delete(key);
    }

    public boolean deleteObjects(final String key) {
        Set<String> keys = redisTemplate.keys(key + "*");
        Long delete = redisTemplate.delete(keys);
        //根据状态修改
        if (delete == 0) {
            return false;
        } else {
            return true;
        }
    }


    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection) {
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList) {
        redisTemplate.delete(key);
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        expire(key,ThirtySecond,TimeUnit.SECONDS);
        return count == null ? 0 : count;
    }

    public <T> long addCacheListHead(final String key, final List<T> dataList) {
        Long count = redisTemplate.opsForList().leftPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    public <T> boolean addCacheZSet(final String key, final List<T> dataList, double score) {
        return redisTemplate.boundZSetOps(key).add(dataList.get(0), score);
    }

    public <T> Set<T> getCacheZSet(final String key, double start, double end) {
        return redisTemplate.boundZSetOps(key).rangeByScore(start, end);
    }

    public <T> Set<T> getCacheZSetRange(final String key, long start, long end) {
        return redisTemplate.boundZSetOps(key).range(start, end);
    }

    public <T> Set<T> getCacheZSetReverse(final String key, long start, long end) {
        return redisTemplate.boundZSetOps(key).reverseRange(start, end);
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    public <T> List<T> getCacheList(final String key, int start, int end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext()) {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key   Redis键
     * @param hKey  Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key  Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }


    public Long incr(String key, int expire) {
        Long value = 0L;
        try {
            value = redisTemplate.getConnectionFactory().getConnection().incr(redisTemplate.getKeySerializer().serialize(key));
            if (expire > 0 && value > 0L) redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    public Long incr(String key, Long expire, TimeUnit timeUnit) {
        Long value = 0L;
        try {
            value = redisTemplate.getConnectionFactory().getConnection().incr(redisTemplate.getKeySerializer().serialize(key));
            if (expire > 0 && value > 0L) redisTemplate.expire(key, expire, timeUnit);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    public Long incr(String key, Long amount, int expire) {
        Long value = 0L;
        try {
            value = redisTemplate.getConnectionFactory().getConnection().incrBy(redisTemplate.getKeySerializer().serialize(key), amount);
            if (expire > 0 && value > 0L) redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    public Long decr(String key) {
        Long value = 0L;
        try {
            value = redisTemplate.getConnectionFactory().getConnection().decr(redisTemplate.getKeySerializer().serialize(key));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    public Long decr(String key, Long amount) {
        Long value = 0L;
        try {
            value = redisTemplate.getConnectionFactory().getConnection().decrBy(redisTemplate.getKeySerializer().serialize(key), amount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    public boolean exits(String key) {
        return redisTemplate.getConnectionFactory().getConnection().exists(redisTemplate.getKeySerializer().serialize(key));
    }

    /**
     * redisTemplate删除迷糊匹配的key的缓存
     */
    public void deleteByPrex(String prex) {
        Set<String> keys = redisTemplate.keys(prex);
        redisTemplate.delete(keys);
    }

    /**
     * 从redis中获取key对应的过期时间;
     * 如果该值有过期时间，就返回相应的过期时间;
     * 如果该值没有设置过期时间，就返回-1;
     * 如果没有该值，就返回-2;
     *
     * @param key
     * @return
     */
    public long expire(String key) {
        return redisTemplate.opsForValue().getOperations().getExpire(key);
    }

    /**
     * 设置key永不过期
     *
     * @param key
     */
    public void persist(String key) {
        redisTemplate.opsForValue().getOperations().persist(key);
    }


    /**
     * 获取redis相关信息
     *
     * @param type
     * @param value
     * @return
     */
    public String connts(String type, String value) {
        Properties info = redisTemplate.getRequiredConnectionFactory().getConnection().info(type);
        return info.getProperty(value);
    }

    public String ping() {
        return (String) redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.ping();
            }
        });
    }


}
